package com.sqx.modules.errand.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.entity.*;
import com.sqx.modules.errand.service.ComplaintService;
import com.sqx.modules.errand.service.IndentService;
import com.sqx.modules.errand.vo.BasicsVo;
import com.sqx.modules.utils.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
@RestController
@RequestMapping("/app/indent")
@Api(value = "订单", tags = {"订单"})
public class IndentController {

    @Autowired
    private IndentService indentService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private ComplaintService complaintService;
    @Autowired
    private UserService userService;

    private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Login
    @PostMapping(value = "distance")
    @ApiOperation("根据经纬度计算两点之间距离")
    public Result distance(Double ol, Double od, Double dl, Double dd, Integer type) {
        return indentService.distance(ol, od, dl, dd, type);
    }


    @Login
    @ApiOperation("获取订单起点附近所有师傅")
    @GetMapping(value = "findVicinityRider")
    public Result findVicinityRider(Double lng, Double lat) {

        return indentService.findVicinityRider(lng, lat);
    }


    @Login
    @GetMapping(value = "basicsMoney")
    @ApiOperation("计算订单基础价格")
    public Result basicsMoney(@RequestAttribute("userId") Long userId, BasicsVo basicsVo) {

        return indentService.basicsMoney(userId, basicsVo);
    }

    @Login
    @PostMapping(value = "addIndent")
    @ApiOperation("用户下单")
    public Result addIndentBuy(@RequestAttribute Long userId, @RequestBody Indent indent) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            if (indent.getAddType() == 1) {
                indent.setUserId(userId);
            } else {
                indent.setRiderUserId(userId);
            }
            return indentService.addIndentBuy(indent);
        } catch (Exception e) {
            log.error("下单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");


    }

    @Login
    @GetMapping(value = "getMyHaveOrder")
    @ApiOperation("获取正在进行中的订单")
    public Result getMyHaveOrder(@RequestAttribute Long userId) {
        return Result.success().put("data", indentService.getOne(new QueryWrapper<Indent>().eq("user_id", userId).in("indent_state", 0, 1, 2, 3)));
    }


    @Login
    @GetMapping(value = "findNewIndent")
    @ApiOperation("师傅查看接单池")
    public Result findNewIndent(@RequestAttribute Long userId, Integer page, Integer limit, Double ol, Double od, Indent indent) {
        return Result.success().put("data", indentService.findNewIndent(userId, page, limit, ol, od, indent));
    }

    @Login
    @GetMapping(value = "riderGetIndentInfo")
    @ApiOperation("师傅查看接单池订单详情")
    public Result riderGetIndentInfo(@RequestAttribute("userId") Long userId, String indentNumber) {
        return Result.success().put("data", indentService.riderGetIndentInfo(userId, indentNumber));
    }


    @Login
    @PostMapping(value = "indentReceiving")
    @ApiOperation("师傅接单")
    public Result indentReceiving(@RequestAttribute Long userId, String indentNumber) {
        return indentService.indentReceiving(userId, indentNumber);
    }

    @Login
    @GetMapping(value = "getRiderIndentList")
    @ApiOperation("师傅查看我的订单")
    public Result getRiderIndentList(@RequestAttribute Long userId, Integer page, Integer limit, String indentState) {

        return Result.success().put("data", indentService.getRiderIndentList(userId, page, limit, indentState));
    }
    @Login
    @GetMapping(value = "riderWaitDrive")
    @ApiOperation("到达出发点位置")
    public Result riderWaitDrive(@RequestAttribute Long userId,Long indentId){
        return indentService.riderWaitDrive(userId,indentId);
    }

    @Login
    @PostMapping(value = "riderStartDrive")
    @ApiOperation("开始服务")
    public Result riderStartDrive(@RequestAttribute Long userId, Long indentId) {
        return indentService.riderStartDrive(userId, indentId);
    }

    //师傅已送达
    @Login
    @PostMapping(value = "riderDelivery")
    @ApiOperation("师傅完成订单")
    public Result riderDelivery(@RequestAttribute Long userId, String indentId) {

        return indentService.riderDelivery(userId, indentId);
    }


    @Login
    @GetMapping(value = "userIndentMessage")
    @ApiOperation("用户查看订单详情")
    public Result userIndentMessage(String indentNumber) {
        return Result.success().put("data", indentService.userIndentMessage(indentNumber));
    }


    @Login
    @PostMapping(value = "riderCancelIndent")
    @ApiOperation("师傅取消订单")
    public Result riderCancelIndent(@RequestAttribute Long userId, String indentId) {

        return indentService.riderCancelIndent(userId, indentId);
    }

    @Login
    @PostMapping(value = "userCancleIndent")
    @ApiOperation("用户取消订单")
    public Result userCancleIndent(@RequestAttribute Long userId, String indentNumber) {

        return indentService.userCancleIndent(userId, indentNumber);
    }

    @Login
    @GetMapping(value = "findUserIndent")
    @ApiOperation("用户查看自己所有订单")
    public Result findUserIndent(@RequestAttribute Long userId, Integer page, Integer limit, Indent indent) {
        indent.setUserId(userId);
        return Result.success().put("data", indentService.findUserIndent(page, limit, indent));
    }

    @Login
    @ApiOperation("用户投诉订单")
    @PostMapping(value = "insertComplaint")
    public Result insertComplaint(@RequestBody SysComplaint sysComplaint) {

        return complaintService.insertComplaint(sysComplaint);
    }

    @Login
    @ApiOperation("用户获取投诉列表")
    @GetMapping(value = "getUserComplaint")
    public Result getUserComplaint(@RequestAttribute("userId") Long userId, Integer page, Integer limit) {
        return Result.success().put("data", complaintService.getUserComplaint(userId, page, limit));
    }

    @Login
    @PostMapping(value = "userEvaluate")
    @ApiOperation("用户评价（评价等级和内容）")
    public Result userEvaluate(@RequestAttribute Long userId, @RequestBody Evaluate evaluate) {

        return indentService.userEvaluate(userId, evaluate);
    }

    @Login
    @GetMapping(value = "findAllComplaint")
    @ApiOperation("师傅查看自己的所有被投诉")
    public Result findAllComplaint(@RequestAttribute Long userId, Integer illegalId, Integer complaintState, Integer page, Integer limit) {

        return complaintService.findAllComplaint(userId, illegalId, complaintState, page, limit);
    }

    @Login
    @GetMapping(value = "findComplaint")
    @ApiOperation("师傅查看被投诉内容")
    public Result findComplaint(@RequestAttribute Long userId, Long complaintId) {

        return complaintService.findComplaint(userId, complaintId);
    }

    @Login
    @PostMapping(value = "appealIndent")
    @ApiOperation("师傅提交申诉")
    public Result appealIndent(@RequestAttribute Long userId, @RequestBody SysComplaint sysComplaint) {

        return complaintService.appealIndent(userId, sysComplaint);
    }

    @Login
    @ApiOperation("培训中心")
    @GetMapping(value = "trainingCenter")
    public Result trainingCenter() {
        CommonInfo one = commonInfoService.findOne(247);
        return Result.success().put("data", one);
    }

    @Login
    @ApiOperation("转单")
    @PostMapping("/transferOfOrder")
    public Result transferOfOrder(Long indentId, String phone) {
        UserEntity userEntity = userService.queryByPhone(phone);
        if (userEntity == null) {
            return Result.error("用户不存在！");
        }
        if (userEntity.getOnLineFlag() != 1) {
            return Result.error("师傅未上线");
        }
        int count = indentService.count(new QueryWrapper<Indent>().eq("rider_user_id", userEntity.getUserId()).in("indent_state", 1, 2));
        if (count > 0) {
            return Result.error("当前师傅有暂未完成的订单");
        }
        CommonInfo one1 = commonInfoService.findOne(261);
        double cashDeposit = Double.parseDouble(one1.getValue());
        if (!"1".equals(userEntity.getCheckCertification())) {
            return Result.error("师傅未进行实名认证！");
        }
        if (userEntity.getCashDeposit().doubleValue() < cashDeposit) {
            return Result.error("师傅保证金不足！");
        }
        int minScore = Integer.parseInt(commonInfoService.findOne(365).getValue());
        if (userEntity.getCreditScore() < minScore) {
            return Result.error("对方信用分不足");
        }
        Indent indent = indentService.getById(indentId);
        if (userEntity.getUserId().equals(indent.getRiderUserId())) {
            return Result.error("不能选择自己！");
        }
        indent.setRiderUserId(userEntity.getUserId());
        indent.setIsTransfer(1);
        indentService.updateById(indent);
        UserEntity user = userService.getById(indent.getUserId());
        CommonInfo one = commonInfoService.findOne(307);
        List<String> msgList = new ArrayList<>();
        msgList.add(0, indent.getIndentNumber());
        if (indent.getIndentState() == 1) {
            msgList.add(1, "已接单");
        } else if (indent.getIndentState() == 2) {
            msgList.add(1, "进行中");
        } else if (indent.getIndentState() == 3) {
            msgList.add(1, "待支付");
        }
        msgList.add(2, "师傅已更换，新师傅将尽快为您送达");
        msgList.add(3, DateUtils.format(new Date()));
        if (StringUtils.isNotEmpty(user.getOpenId())) {
            SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 3);
        }
        if (StringUtils.isNotEmpty(user.getClientid())) {
            userService.pushToSingle("更换师傅", "师傅已更换，新师傅将尽快为您送达", user.getClientid());
        }
        return Result.success();
    }

    @GetMapping("/getProfitList")
    @ApiOperation("师傅收益排行榜")
    public Result getProfitList(Integer page, Integer limit, String time, Integer flag) {
        return Result.success().put("data", indentService.getProfitList(page, limit, time, flag));
    }

    @Login
    @GetMapping("/getOrderSubscript")
    @ApiOperation("订单角标")
    public Result getOrderSubscript(@RequestAttribute("userId") Long userId) {
        return Result.success().put("data", indentService.getOrderSubscript(userId));
    }

}
